package com.youlai.boot.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.system.converter.DictConverter;
import com.youlai.boot.system.converter.DictDataConverter;
import com.youlai.boot.system.mapper.DictMapper;
import com.youlai.boot.system.model.entity.SysDictDataEntity;
import com.youlai.boot.system.model.entity.SysDictEntity;
import com.youlai.boot.system.model.form.DictForm;
import com.youlai.boot.system.model.query.DictPageQuery;
import com.youlai.boot.system.model.vo.DictPageVO;
import com.youlai.boot.system.model.vo.DictVO;
import com.youlai.boot.system.service.DictDataService;
import com.youlai.boot.system.service.DictService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.mybatisflex.core.query.QueryMethods.*;

/**
 * 数据字典业务实现类
 *
 * @author haoxr
 * @since 2022/10/12
 */
@Service
@RequiredArgsConstructor
public class DictServiceImpl extends ServiceImpl<DictMapper, SysDictEntity> implements DictService {

    private final DictDataService dictDataService;
    private final DictConverter dictConverter;
    private final DictDataConverter dictDataConverter;

    /**
     * 字典分页列表
     *
     * @param queryParams 分页查询对象
     */
    @Override
    public Page<DictPageVO> getDictPage(DictPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();

        // 查询数据
        QueryWrapper query = QueryWrapper.create().from(SysDictEntity.class)
                .and(q -> {
                    q.and(SysDictEntity::getName).like(queryParams.getKeywords())
                            .or(SysDictEntity::getDictCode).like(queryParams.getKeywords());
                }, StrUtil.isNotBlank(queryParams.getKeywords()));

        return this.pageAs(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                query,
                DictPageVO.class
        );
    }

    /**
     * 新增字典
     *
     * @param dictForm 字典表单数据
     */
    @Override
    public boolean saveDict(DictForm dictForm) {
        // 保存字典
        SysDictEntity entity = dictConverter.toEntity(dictForm);

        // 校验 code 是否唯一
        String dictCode = entity.getDictCode();

        long count = this.count(QueryWrapper.create()
                .eq(SysDictEntity::getDictCode, dictCode)
        );

        Assert.isTrue(count == 0, "字典编码已存在");

        return this.save(entity);
    }


    /**
     * 获取字典表单详情
     *
     * @param id 字典ID
     */
    @Override
    public DictForm getDictForm(Long id) {
        // 获取字典
        SysDictEntity entity = this.getById(id);
        if (entity == null) {
            throw new BusinessException("字典不存在");
        }
        return dictConverter.toForm(entity);
    }

    /**
     * 修改字典
     *
     * @param id       字典ID
     * @param dictForm 字典表单
     */
    @Override
    public boolean updateDict(Long id, DictForm dictForm) {
        // 更新字典
        SysDictEntity entity = dictConverter.toEntity(dictForm);

        // 校验 code 是否唯一
        String dictCode = entity.getDictCode();
        long count = this.count(
                QueryWrapper.create()
                        .eq(SysDictEntity::getDictCode, dictCode)
                        .ne(SysDictEntity::getId, id)
        );
        if (count > 0) {
            throw new BusinessException("字典编码已存在");
        }

        return this.updateById(entity);
    }

    /**
     * 删除字典
     *
     * @param ids 字典ID，多个以英文逗号(,)分割
     */
    @Override
    @Transactional
    public void deleteDictByIds(List<String> ids) {
        for (String id : ids) {
            SysDictEntity dict = this.getById(id);
            if (dict != null) {
                boolean removeResult = this.removeById(id);
                // 删除字典下的字典项
                if (removeResult) {
                    dictDataService.remove(
                            QueryWrapper.create()
                                    .eq(SysDictDataEntity::getDictCode, dict.getDictCode())
                    );
                }

            }
        }
    }

    /**
     * 获取字典列表（包含字典数据）
     */
    @Override
    public List<DictVO> getAllDictWithData() {

        QueryWrapper query = QueryWrapper.create().from(SysDictEntity.class)
                .select(column(SysDictEntity::getName), column(SysDictEntity::getDictCode))
                .and(SysDictEntity::getStatus).eq(1)
                .orderBy(SysDictEntity::getCreatedAt).desc();

        return this.mapper.selectListWithRelationsByQueryAs(query,DictVO.class);
    }
}




